<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Dynamic Data Binding Example</title>
</head>
<body>

<!-- 自定义元素 -->
<counter-element value="1" step="1"></counter-element>
<counter-element value="5" step="2"></counter-element>

<!-- 模板 -->
<template id="counter-template">
    <style>
        .counter {
            padding: 10px;
            border: 1px solid #ccc;
            display: inline-block;
        }
        button {
            margin: 0 5px;
        }
    </style>
    <div class="counter">
        <button id="decrease">-</button>
        <span id="value"></span>
        <button id="increase">+</button>
    </div>
</template>

<script>
    // 定义自定义元素类
    class CounterElement extends HTMLElement {
        static get observedAttributes() {
            return ['value', 'step']; // 监听的属性列表
        }

        constructor() {
            super();
            const shadowRoot = this.attachShadow({ mode: 'open' });
            const template = document.getElementById('counter-template').content.cloneNode(true);
            shadowRoot.appendChild(template);

            // 初始化属性值
            this._value = parseInt(this.getAttribute('value')) || 0;
            this._step = parseInt(this.getAttribute('step')) || 1;

            // 获取DOM元素
            this.valueEl = shadowRoot.querySelector('#value');
            this.decreaseBtn = shadowRoot.querySelector('#decrease');
            this.increaseBtn = shadowRoot.querySelector('#increase');

            // 设置初始值
            this.updateValue();

            // 绑定事件
            this.decreaseBtn.addEventListener('click', () => this.decrease());
            this.increaseBtn.addEventListener('click', () => this.increase());
        }

        // 当属性发生变化时调用
        attributeChangedCallback(name, oldValue, newValue) {
            console.log(`属性${name}发生变化，旧值：${oldValue}，新值：${newValue}`)
            if (name === 'value') {
                this._value = parseInt(newValue);
                this.updateValue();
            } else if (name === 'step') {
                this._step = parseInt(newValue);
            }
        }

        // 更新显示的值
        updateValue() {
            this.valueEl.textContent = this._value;
        }

        // 减少计数
        decrease() {
            this._value -= this._step;
            this.setAttribute('value', this._value); // 更新属性值
        }

        // 增加计数
        increase() {
            this._value += this._step;
            this.setAttribute('value', this._value); // 更新属性值
        }
    }

    // 注册自定义元素
    customElements.define('counter-element', CounterElement);
</script>

</body>
</html>
